--[[
    商店格子类
]]
local shopItem = BaseClass("shopItem")

function shopItem : __init(shopItem, goodDate)
    -- 查找组件
    self.shopItem = shopItem
    self.goodDate = goodDate
    goodDate.shopItemInstance = self
    self.iconBackground = self.shopItem.transform : Find("IconBackground") : GetComponent("Image")
    self.imgIcon = self.iconBackground.transform : Find("Icon") : GetComponent("Image")
    self.countText = self.iconBackground.transform : Find("Count") : GetComponent("Text")
    self.nameText = self.shopItem.transform : Find("Name") : GetComponent("Text")
    self.priceText = self.shopItem.transform : Find("Price") : GetComponent("Text")
    self.Description = self.shopItem.transform : Find("Description") : GetComponent("Text")

    -- 赋值
    local globalItemCount = self : FindInitGlobalDate(goodDate.id)
    if globalItemCount then
        goodDate.count = globalItemCount.count
    end

    local sprite = Resources.Load("Icon/" .. self.goodDate.icon, typeof(CS.UnityEngine.Sprite))
    self.imgIcon.sprite = sprite
    self.nameText.text = "名称："..self.goodDate.name
    self : RefreshCountText(self.goodDate.count)
    self.priceText.text = "价格:"..self.goodDate.price
    self.Description.text = "<color=black>物品描述</color>\n"..self.goodDate.description

    -- 添加点击事件
    self : AddClickEvent() 
end

function shopItem : FindInitGlobalDate(id)
    if Global.GoodsDate then
        for _, item in ipairs(Global.GoodsDate) do
            if item.id == id then
                return item;
            end
        end
    end
    return nil;
end

-- 刷新商品数量文本
function shopItem : RefreshCountText(count)
    local globalItemCount = self : FindInitGlobalDate(self.goodDate.id)
    if globalItemCount then
        self.countText.text = "x"..globalItemCount.count
    else
        self.countText.text = "x"..count
    end
end

-- 添加点击事件
function shopItem : AddClickEvent()
    local eventTrigger = self.shopItem : GetComponent(typeof(CS.UnityEngine.EventSystems.EventTrigger))
    if not eventTrigger then
        eventTrigger = self.shopItem : AddComponent(typeof(CS.UnityEngine.EventSystems.EventTrigger))
    end

    local entry = CS.UnityEngine.EventSystems.EventTrigger.Entry()
    entry.eventID = CS.UnityEngine.EventSystems.EventTriggerType.PointerClick
    entry.callback : AddListener(function(eventData)
        self : OnClick(eventData) 
    end)

    eventTrigger.triggers : Add(entry)
end

-- 点击商品格子
function shopItem : OnClick(eventData)
    local globalItem = self:FindInitGlobalDate(self.goodDate.id)
    Global.SelectItemDate = globalItem or self.goodDate
    print("ShopItem输出1：选择物品名称"..Global.SelectItemDate.name)
end

return shopItem